<script setup lang="ts">
import { ref, onMounted } from 'vue'
import TnSwiper from '@tuniao/tnui-vue3-uniapp/components/swiper/src/swiper.vue';
import HomeCard from '@/composables/card/HomeCardV2.vue';
import TypeFilter from "./components/TypeFilter.vue";
import TimeFilter from "./components/TimeFilter.vue";
import TipCard from "@/composables/card/TipCard.vue";
import { projectListApi } from "@/api/home";
import {getNavBarHeight} from "@/utils/navBarHeight";
import HomeCardSkeleton from "@/composables/card/HomeCardSkeleton.vue";
import NoData from "@/composables/noData/NoData.vue";
import {getToken} from "@/utils/userInfo";
const currentSwiperIndex = ref<number>(0)
const scrollY = ref(false);
// 轮播图数据
const swiperData: Array<string> = [
  'https://lemawuyou.oss-cn-shanghai.aliyuncs.com/client/shanghuduan/banner.png',
  'https://lemawuyou.oss-cn-shanghai.aliyuncs.com/client/shanghuduan/banner1.png',
  'https://lemawuyou.oss-cn-shanghai.aliyuncs.com/client/shanghuduan/banner3.png',
  'https://lemawuyou.oss-cn-shanghai.aliyuncs.com/client/shanghuduan/banner2.png',
]

const dataList = ref<any>([]);
const loading = ref(false);
const getData = async (additionalServices = "", categorySelectionTwo = "", beginPrice = "", endPrice = "", num = 0) => {
  if (num > 2) {
    return;
  }
  const res = await projectListApi({
    beginPrice: beginPrice,
    endPrice: endPrice,
    lastId: "",
    size: 10,
    categorySelectionTwo: categorySelectionTwo,
    categorySelectionOne: additionalServices,
    keyword: keyword.value
  })
  if(res?.code !== 200) {
    setTimeout(() => {
      getData(additionalServices = "", categorySelectionTwo = "", beginPrice = "", endPrice = "", num++);
    }, 1000)
    return;
  }
  dataList.value = res?.data || [];
}

const onScroll = (e: any) => {

  const { scrollTop, scrollHeight, clientHeight } = e.detail
  const bottomDistance = scrollHeight - scrollTop - clientHeight
  // 当距离底部小于 50px 时加载更多
  if (bottomDistance < 50) {

  }
}

onMounted(async () => {
  loading.value = true;
  getToken().then(() => {
    setTimeout(() => {
      typeFilterRef.value.init(0);
      getData(typeFilterRef?.value?.code || "");
      loading.value = false;
    }, 1000);
  })
});


const timeFilterRef = ref();
const searchType = (data: any, categorySelectionTwo: string) => {
  getData(data, categorySelectionTwo, timeFilterRef.value.minPrice, timeFilterRef.value.maxPrice);
}

const typeFilterRef = ref();
const searchTime = (beginPrice: string, endPrice: string) => {
  getData(typeFilterRef.value.code, typeFilterRef.value.childrenCode, beginPrice, endPrice)
}

const setScroll = (value: boolean) => {
  scrollY.value = value;
}



const keyword = ref("");
// 搜索框动画状态
const searchScale = ref(1); // 缩放比例
const searchTranslateY = ref(0); // 垂直位移
const searchTranslateX = ref(0);
const searchOpacity = ref(1); // 透明度
const searchWidth = ref(100);
// 固定参数
const MAX_SCROLL = 100; // 滚动超过 100px 完全吸顶
const MAX_TRANSLATE = -95; // 向上平移距离
const MIN_SCALE = 0.8; // 最小缩放

const handleScroll = (scrollTop: any) => {
  // 限制范围
  const ratio = Math.min(scrollTop.scrollTop / MAX_SCROLL, 1);

  // 动态计算动画参数
  searchScale.value = 1 - ratio * (1 - MIN_SCALE);
  searchTranslateY.value = ratio * MAX_TRANSLATE;
  if (searchTranslateY.value < -50) {
    searchTranslateY.value = -50;
  }
  if(searchTranslateY.value > 0) {
    searchTranslateY.value = 0;
  }
  if(searchTranslateY.value < -50) {
    searchTranslateY.value = 50;
  }
  searchOpacity.value = 1 - ratio * 0.2; // 滚动时稍微透明
  searchTranslateX.value = ratio * 25;

  // 计算宽度缩小比例
  const maxScroll = 100; // 最大滚动距离
  const minWidthPercent = 55; // 最小50%
  const widthPercent = 100 - Math.min(scrollTop.scrollTop, maxScroll) / maxScroll * (100 - minWidthPercent);
  searchWidth.value = widthPercent;
};

const refresherTriggered = ref(false);
const refresherrefresh = () => {
  refresherTriggered.value = true;
  setTimeout(async () => {
    await getData(typeFilterRef.value.code, typeFilterRef.value.childrenCode, timeFilterRef.value.minPrice, timeFilterRef.value.maxPrice);
    refresherTriggered.value = false;
  }, 500);
}

const scrolltolower = async () => {
  console.log("触底了");
  const lastId = dataList?.value[dataList?.value?.length - 1]?.id
  const params = {
    beginPrice: timeFilterRef.value.minPrice,
    endPrice: timeFilterRef.value.maxPrice,
    lastId: "",
    size: 10,
    categorySelectionTwo: typeFilterRef.value.childrenCode,
    categorySelectionOne: typeFilterRef.value.code,
  }
  if (lastId) {
    params.lastId = lastId;
  }
  const res = await projectListApi(params)
  if(res?.code === 200) {
    const newList = res?.data || [];
    dataList.value = [...dataList.value, ...newList];
  }
}

const tipList = [
  {
    title: "平台规则",
    icon: "creative",
    url: "/pages/user/platformRules/index",
  },
  {
    title: "接单流程",
    icon: "clock",
    url: "/pages/user/orderProcess/index",
  },
  {
    title: "消息公告",
    icon: "notice",
    url: "",
  },

]

defineExpose({
  getData,
  setScroll,
  handleScroll
})
</script>

<template>
  <view>
    <view class="search-navbar-home" :style="{ height: getNavBarHeight() + 'px', paddingTop: getNavBarHeight() - 40 + 'px' }">
      <image
          src="https://cdn.nlark.com/yuque/0/2023/png/280373/1679989824360-assets/web-upload/d6f05bc7-7e47-4566-98fc-494350f4f5d2.png"
          class="nav-icon"
          style="width: 30px; height: 30px"
      />

      <view style="margin-left: 10px; font-weight: bold; color: #000000" :style="{ opacity: searchWidth === 100 ? 100 : searchWidth / 100 }">
        <button style="display: inline; height: 10px; font-size: 14px; margin-top: -10px; background: #ffffff" open-type="share">乐码无忧</button>
        </view>
    </view>
    <view class="page" @scroll="onScroll">
      <view
          class="search-box"
          :style="{
        transform: `scale(${searchScale}) translateY(${searchTranslateY}px) translateX(${searchTranslateX}px)`,
        top: getNavBarHeight() - 3 + 'px',
         width: searchWidth + '%',
      }"
      >
        <view class="search-input">
          <text class="icon">🔍</text>
          <input type="text" placeholder="搜索订单/程序" v-model="keyword" @blur="getData()" @keyup.enter="getData()" />
        </view>
      </view>
      <view class="swiper-container">
        <view class="padding-swiper">
          <TnSwiper
              v-model="currentSwiperIndex"
              :data="swiperData"
              width="100%"
              height="280"
          >
            <template #default="{ data }">
              <view class="swiper-data">
                <image class="image" :src="data" alt="" mode="aspectFill" />
              </view>
            </template>
          </TnSwiper>
          <view>
            <TipCard v-for="item in tipList" :key="item.title" :title="item.title" :icon="item.icon" :url="item.url"></TipCard>
          </view>
        </view>
        <view class="flex filter">
          <TypeFilter @submit="searchType" ref="typeFilterRef"></TypeFilter>
          <TimeFilter @getData="searchTime" ref="timeFilterRef" class="filter-left" ></TimeFilter>
        </view>
      </view>
      <HomeCardSkeleton v-if="dataList.length === 0 && loading"></HomeCardSkeleton>
      <no-data v-if="dataList.length === 0 && !loading"></no-data>
      <scroll-view v-if="dataList.length > 0" style="height: calc(100vh - 340rpx)" :scroll-y="scrollY" @scrolltolower="scrolltolower" :refresher-enabled="!scrollY" @refresherrefresh="refresherrefresh" :refresher-triggered="refresherTriggered">
        <view>
          <view class="scroll-container">
            <HomeCard :dataList="dataList" @scroll="onScroll" scroll-y></HomeCard>

          </view>
          <view style="height: 120rpx"></view>
        </view>
        <view></view>
      </scroll-view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.page {
  padding-top: calc(20px + 44px + 44px); /* 状态栏 + 导航栏高度 */
  padding-bottom: 100rpx; /* TabBar 高度 */
}
.swiper-container {

  .padding-swiper {
    padding: 0 30rpx 20rpx 30rpx;
    width: 100%;
    display: flex;
  }
  .swiper-data {
    width: 100%;
    height: 100%;
    border-radius: 20rpx;

    .image {
      width: 100%;
      height: 100%;
      border-radius: inherit;
    }
  }
  .filter {
    padding: 0 30rpx 5px;
    .filter-left {
      margin-left: 50rpx;
    }
  }
  .scroll-container {
    height: 100%;
    overflow-y: auto;

  }
}
.logo-pic {
  image {
    width: 30px;
    height: 30px;
  }
}
.logo-pic-img {
  width: 30px;
  height: 30px;
}
/* 旋转 */
.png-sussuspension1 {
  animation: suspension1 12s ease-in-out infinite;
}
.tn-navbar__wrapper {
  top: 0 !important;
}

.search-box {
  position: fixed;
  left: 0;
  right: 0;
  padding: 0 16px;
  transition: transform 0.2s ease, opacity 0.2s ease;
  z-index: 1000;
}

.search-input {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 24px;
  padding: 8px 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  font-size: 14px;
}

.search-input .icon {
  margin-right: 8px;
  font-size: 16px;
}

.search-input input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
}
.search-navbar-home {
  background: #ffffff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  padding-left: 15px;
}
.nav-icon {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  animation: rotate 5s linear infinite;
}
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
